//
//  ViewController.m
//  TagPointerDemo2
//
//  Created by FelixYin on 2020/4/12.
//  Copyright © 2020 FelixYin. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,copy) NSString *name;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self test1];
//    [self test2];
//    [self test3];
}

- (void) test1{
    /*
     当字符串长度达到一个指针地址没法保存的时候，字符串会变成一个NSString去存储，当可以保存的时候会使用64bit之后推出的
     TaggedPointer去存当前值，当使用的是TaggedPointer保存值的时候 不会担心多线程 同时操作一个指针的问题，但不是TaggedPointer而是NSString时，在赋值的时候会是多线程同时操作一个变量，会造成
     坏内存访问
     */
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    for (int i = 0; i < 1000; i++) {
        dispatch_async(queue, ^{
            self.name = [NSString stringWithFormat:@"abcdefgijkrstabcdefgijkrstabcdefgijkrstabcdefgijkrst"];
            NSLog(@"=== name %@  class===%@",self.name,[self.name class]);
        });
    }
}


- (void) test2{
    //此时不会造成坏内存访问
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    for (int i = 0; i < 1000; i++) {
        dispatch_async(queue, ^{
            self.name = [NSString stringWithFormat:@"abcd"];
            
            NSLog(@"=== name %@",self.name);
        });
    }
}


- (void) test3{
    NSString *str1 = [NSString stringWithFormat:@"abcdefgijk"];
    NSString *str2 = [NSString stringWithFormat:@"2345abc"];
    NSLog(@"str1 === %@   str2 === %@",[str1 class],[str2 class]);
    NSLog(@"str1 === %p   str2 === %p",str1,[str2 class]);
}


@end
